package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import controller.AuthenticationController;
import dto.AuthenticationDTO;

public class FramePreferences extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private JTextField txtUsername;
	private JTextField txtPassword;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					// Using Look-and-Feel Windows for this application.
					try {
						for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
								.getInstalledLookAndFeels()) {
							if ("Windows".equals(info.getName())) {
								javax.swing.UIManager.setLookAndFeel(info
										.getClassName());
								break;
							}
						}
					} catch (ClassNotFoundException ex) {
						java.util.logging.Logger
								.getLogger(DBMS.class.getName()).log(
										java.util.logging.Level.SEVERE, null,
										ex);
					} catch (InstantiationException ex) {
						java.util.logging.Logger
								.getLogger(DBMS.class.getName()).log(
										java.util.logging.Level.SEVERE, null,
										ex);
					} catch (IllegalAccessException ex) {
						java.util.logging.Logger
								.getLogger(DBMS.class.getName()).log(
										java.util.logging.Level.SEVERE, null,
										ex);
					} catch (javax.swing.UnsupportedLookAndFeelException ex) {
						java.util.logging.Logger
								.getLogger(DBMS.class.getName()).log(
										java.util.logging.Level.SEVERE, null,
										ex);
					}

					FramePreferences frame = new FramePreferences();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public FramePreferences() {
		setTitle("Preferences");
		setIconImage(Toolkit.getDefaultToolkit().getImage(
				DBMS.class.getResource("images/preference-icon.png")));
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));

		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new GridLayout(0, 3, 10, 5));

		JLabel lblUserName = new JLabel("User name : ");
		lblUserName.setHorizontalAlignment(SwingConstants.RIGHT);
		panel_1.add(lblUserName);

		txtUsername = new JTextField();
		txtUsername.setText("username");
		panel_1.add(txtUsername);
		txtUsername.setColumns(10);

		JLabel lblNewLabel = new JLabel("");
		panel_1.add(lblNewLabel);

		JLabel lblPassword = new JLabel("Password : ");
		lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		panel_1.add(lblPassword);

		txtPassword = new JTextField();
		txtPassword.setText("password");
		panel_1.add(txtPassword);
		txtPassword.setColumns(10);

		JLabel label = new JLabel("");
		panel_1.add(label);

		JPanel panel_2 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_2.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		panel.add(panel_2, BorderLayout.SOUTH);

		JButton btnAdd = new JButton("Add");
		btnAdd.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String usrname = txtUsername.getText();
				String password = txtPassword.getText();
				if (usrname == null || password == null) {
					return;
				}

				AuthenticationController authCtrl = new AuthenticationController(
						usrname, password);
				try {
					if (authCtrl.createAccount()) {
						JOptionPane.showMessageDialog(table,
								"Create account successful");
						reloadAccountToTable();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
					JOptionPane.showMessageDialog(table,
							"Create account unsuccessful");
				}
			}
		});
		panel_2.add(btnAdd);

		JButton btnRemove = new JButton("Remove");
		btnRemove.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// 1. Get selected account from table
				ListSelectionModel model = table.getSelectionModel();
				int selectedIndex = model.getLeadSelectionIndex();
				String usrname = table.getValueAt(selectedIndex, 0).toString();
				String password = table.getValueAt(selectedIndex, 1).toString();
				AuthenticationController authCtrl = new AuthenticationController(
						usrname, password);
				try {
					if (authCtrl.removeAccount()) {
						JOptionPane.showMessageDialog(table,
								"Remove account successful");
						reloadAccountToTable();
					}
				} catch (Exception e2) {
					JOptionPane.showMessageDialog(table,
							"Remove account unsuccessful");
				}
			}
		});
		panel_2.add(btnRemove);

		JButton btnRefresh = new JButton("Refresh");
		btnRefresh.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				reloadAccountToTable();
			}
		});
		panel_2.add(btnRefresh);

		JButton btnClose = new JButton("Close");
		btnClose.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				dispose();
			}
		});
		panel_2.add(btnClose);

		JPanel panelbutton = new JPanel();
		contentPane.add(panelbutton, BorderLayout.SOUTH);

		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);

		table = new JTable();
		table.setModel(new DefaultTableModel(
				new Object[][] { { null, null }, }, new String[] { "User Name",
						"Password" }) {
			boolean[] columnEditables = new boolean[] { false, false };

			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		scrollPane.setViewportView(table);
		reloadAccountToTable();
	}

	private void reloadAccountToTable() {
		AuthenticationController ctrl = new AuthenticationController();
		ArrayList<AuthenticationDTO> accounts = null;
		try {
			accounts = ctrl.getAllAccounts();
			DefaultTableModel model = new DefaultTableModel();
			model.setColumnIdentifiers(new Object[] { "User Name", "Password" });

			// add accounts to table
			if (accounts != null) {
				for (AuthenticationDTO account : accounts) {
					model.addRow(new Object[] { account.get_username(),
							account.get_password() });
				}
			}

			table.setModel(model);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(table, e.getMessage());
		}
	}

}
